<?php
/**
 * Created by PhpStorm.
 * Author: sitewang@aliyun.com
 * CreateTime: 2022/4/11 6:08 PM
 * Blog：www.myblogs.xyz
 */

namespace App\Http\Controllers\Admin;

use App\Models\Setting;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Session;

class LoginController extends Controller
{
    public function index()
    {
        // 获取站点信息
        $setting_model = new Setting();
        $site = $setting_model->settingFind('site');

        return view('admin.login', compact('site'));
    }

    public function into(Request $request)
    {
        // 账户登录
        $data = $request->post();
        if (!empty($data)){
            unset($data['_token']);
            if (empty($data['username'])){
                return self::jsonReturn(1001, '', '请输入登录账户');
            }
            if (empty($data['password'])){
                return self::jsonReturn(1001, '', '请输入账号密码');
            }
            $user_model = new User();
            $user_data = $user_model->getFind(['username'=>$data['username']]);
            if (empty($user_data)){
                return self::jsonReturn(1001, '', '该账户不存在');
            }
            if ($user_data->password != md5($data['password'])){
                return self::jsonReturn(1001, '', '您的登录密码有误');
            }
            if ($user_data->status == 1){
                return self::jsonReturn(1001, '', '您的账户已被锁定');
            }
            if (empty($user_data->role_id)){
                return self::jsonReturn(1001, '', '您的没有登录权限');
            }
            $user_id = $user_data->user_id;
            $login_data['last_time'] = NEW_TIME;
            $login_data['last_ip'] = get_client_ip();
            $login_data['user_id'] = $user_id;
            $user_model->operation($login_data, false);
            Session::put('user_id', $user_id);
            Session::save();
            return self::jsonReturn(1000, '', '登录成功');
        }
    }

    public function out()
    {
        Session::put('user_id');
        Session::save();
        return redirect()->route('admin.login');
    }

    public static function jsonReturn($status = 0, $data = '', $message = '')
    {
        $result = [
            'status'   => $status,
            'data'     => $data,
            'message'  => $message,
        ];
        return response()->json($result, 200);
    }

}
